package top.byfree.jbyan.find.handler.impl;

import top.byfree.jbyan.find.FindApplication;
import top.byfree.jbyan.find.exception.ParseArgException;
import top.byfree.jbyan.find.handler.Finder;
import top.byfree.jbyan.find.result.Line;
import top.byfree.jbyan.find.result.MoreKeyResultSet;

import java.util.List;

import static top.byfree.jbyan.find.command.Arg.RANGE;

/**
 * @author jbyan
 * @since 2023/8/9
 */
public class MoreKeyFinder implements Finder<MoreKeyResultSet> {

    /* 保存要检索的关键字列表 */
    private static final List<String> POS_ARGS = FindApplication.ARGS.getPosArgs();
    /* 检索的最大间隔 */
    private static final int RANGE_ARG = FindApplication.ARGS.getIntArg(RANGE);

    @Override
    public void find(String line, int index, MoreKeyResultSet rs) throws ParseArgException {

        // 遍历所有的检索关键字
        POS_ARGS.forEach(key -> {
            // 匹配到关键字，就将当前行加入到优先队列
            if (line.contains(key)) {
                rs.addToPriorityQueue(index, key);
            }
        });

        if (rs.isOpen()) {
            if (index - rs.getFirstIndex() > RANGE_ARG) {
                // 超过了最大指定行数，移除优先队列头元素
                rs.removeFirstElement();
            }
            // 否则将当前行加入到结果当中
            rs.addLine(Line.create(index, line));
        }
    }

    @Override
    public MoreKeyResultSet createResult() {
        return new MoreKeyResultSet();
    }
}
